package cn.bigfire.wzdj.util;

import cn.bigfire.wzdj.pojo.httpVo.WZDJLocalItem;
import cn.bigfire.wzdj.pojo.httpVo.WxCheckQrRes;
import cn.bigfire.wzdj.pojo.httpVo.WxGetCodeRes;
import cn.bigfire.wzdj.pojo.httpVo.WxGetQrRes;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.dongliu.requests.Requests;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class WxApi {

    public static WxGetQrRes getQR() {
        String url = "http://101.34.7.208:8081/api/Login/GetQR";
        HashMap<String,String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        String body = Requests.get(url).headers(headers).body("{}").send().readToText();
//        log.info(body);
        if (JSONUtil.isTypeJSONObject(body)) {
            JSONObject jsonObject = JSONObject.parseObject(body);
//            log.info(jsonObject.toJSONString());
            if (jsonObject.getBooleanValue("Success")) {
                WxGetQrRes wxGetQrRes = jsonObject.getObject("Data", WxGetQrRes.class);
                if (wxGetQrRes != null) {
                    Stores.getInstance().setQrExpired(false);
                    Stores.getInstance().setQrUuid(wxGetQrRes.getUuid());
                }
                return wxGetQrRes;
            }
        }
        return null;
    }

    public static WxCheckQrRes checkQr(String uuid) {
        String checkQrApi = "http://101.34.7.208:8081/api/Login/CheckQR?uuid=" + uuid;
        String readToText = Requests.post(checkQrApi).send().readToText();
        //频率略高，不打印了
//        log.info("checkQrApi:{}", checkQrApi);
//        log.info("result:{}", readToText);
        if (JSONUtil.isTypeJSONObject(readToText)) {
            return JSONObject.parseObject(readToText, WxCheckQrRes.class);
        } else {
            log.error(readToText);
        }
        return null;
    }

//    public static void fileSaveLoginRecord(WXAcctSectResp WXAcctSectResp) {
//        //构建一条数据
//        Date date = new Date();
//        WZDJLocalItem localItem = new WZDJLocalItem();
//        localItem.setLoginTime(date.getTime());
//        localItem.setWxAccountInfo(null);
//        localItem.setShowInfo(String.format("%s(%s)%s", WXAcctSectResp.getNickName(), WXAcctSectResp.getAlias(), DateUtil.formatDateTime(date)));
//        Stores.localJson.put(WXAcctSectResp.getAlias(), localItem);//同一个微信号会覆盖
//        checkRemove(Stores.localJson);//检查移除，如果超过10个，移除老的数据
//        FileUtil.writeString(Stores.localJson.toJSONString(), Stores.localFile, "UTF-8");//写文件
//    }

//    public static void checkRemove(JSONObject jsonObject) {
//        List<WZDJLocalItem> sortedItems = new ArrayList<>();
//        for (Object value : jsonObject.values()) {
//            try {
//                WZDJLocalItem item = JSON.parseObject(JSON.toJSONString(value), WZDJLocalItem.class);
//                sortedItems.add(item);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        sortedItems.sort(Comparator.comparingLong(WZDJLocalItem::getLoginTime));//排序
//        if (jsonObject.size() > 10) {
//            WZDJLocalItem eldestItem = sortedItems.get(0);
//            jsonObject.remove(eldestItem.getWxAccountInfo().getAcctSectResp().getAlias()+"");
//        }
//    }

    public static final String WZDJ_APPID = "wx71702c33334e92bd";//小程序 appid
    public static WxGetCodeRes wxLogin(String appid, String wxId) {
        String url = "http://101.34.7.208:8081/api/Wxapp/JSLogin";
        HttpRequest post = HttpUtil.createPost(url);
        post.header("Content-Type", "application/json");
        JSONObject param = new JSONObject();
        param.put("Appid", appid);
        param.put("WxId", wxId);
        post.body(param.toJSONString());
        String body = post.execute().body();
        if (JSONUtil.isTypeJSONObject(body)) {
            JSONObject jsonObject = JSONObject.parseObject(body);
//            log.info(jsonObject.toJSONString());
            if (jsonObject.getBooleanValue("Success")) {
                WxGetCodeRes wxGetCodeRes = jsonObject.getObject("Data", WxGetCodeRes.class);
                return wxGetCodeRes;
            } else {
                String message = jsonObject.getString("Message");
                log.error("wx协议 服务器 报错信息:" + message);
            }
        }
        return null;
    }

    public static void main(String[] args) {
//        WxGetQrRes wxGetQrRes = getQR();
//        if (wxGetQrRes == null) {
//            return;
//        }
//        log.info(wxGetQrRes.getQrUrl());
//        ThreadUtil.sleep(10 * 1000);
//        WxCheckQrRes wxCheckQrRes = checkQr(wxGetQrRes.getUuid());
//        if (wxCheckQrRes == null) {
//            return;
//        }
//        String wxId = acctSectRes.getUserName();
//        String appId = "wx71702c33334e92bd";//小程序 appid
//        if (StrUtil.isBlank(appId)) {
//            return;
//        }
//        WxLoginRes wxLoginRes = wxLogin(appId, wxId);
//        if (wxLoginRes == null) {
//            return;
//        }
    }

    @Test
    @SneakyThrows
    public void test() {
        String wxId = "wxid_kprryf66nfdo22";
        WxGetCodeRes wxGetCodeRes = WxApi.wxLogin(WxApi.WZDJ_APPID, wxId);
        log.info(wxGetCodeRes.toString());
    }


}
